package com.test.cordova;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.multidex.MultiDex;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.test.cordova.receiver.HomeWatcherReceiver;
import com.test.cordova.service.ServiceManager;
import com.test.cordova.util.Constants;
import com.test.cordova.util.CutoutScreenUtil;
import com.test.cordova.util.Logger;
import com.test.cordova.util.SharedPreferencesUtil;
import com.test.cordova.util.StatusBarUtil;

/**
 * 应用启动初始化
 */

public class StartApplication extends Application{

    private static final String TAG= StartApplication.class.getSimpleName();
    private static Context context;

    public static Context getContext() {
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.context = getApplicationContext();
        //广播监听home键
        homeListener();
        //监听app生命周期
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
    }

    private void homeListener() {
        HomeWatcherReceiver mHomeKeyReceiver = new HomeWatcherReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mHomeKeyReceiver,homeFilter);
    }

    /**
     * 分割 Dex 支持
     *
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    private NotificationManager notificationManager;
    private NotificationCompat.Builder mBuilder;
    private int tempCount;
    private PowerManager pm;
    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            Log.e(TAG,"onActivityCreated "+activity+"sss: "+savedInstanceState);
            // 如果是允许全屏显示到刘海屏区域的刘海屏机型
            if (CutoutScreenUtil.allowDisplayToCutout()) {
                if (isFullScreen(activity)) {
                    // 如果允许通过显示状态栏方式适配刘海屏
                    if (activity instanceof StartActivity) {
                        // 显示状态栏
                        StatusBarUtil.setStatusBar(activity.getWindow(),true);
                    } else {
                        // 需自行将该界面视图元素下移，否则可能会被刘海遮挡

                    }
                } else {
                    // 非全屏界面无需适配刘海屏
                }
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            tempCount++;
            Logger.i(TAG, "onActivityStarted " + activity + " : " + tempCount);
            if (tempCount == 1) {
                //处于前台 初始化安全标记
                if (notificationManager != null) {
                    notificationManager.cancel(1);
                }
                Constants.isSafety = false;
            }
        }

        @Override
        public void onActivityResumed(Activity activity) {
            //处理后台唤醒app
            /*if (!(activity instanceof StartActivity)) {
                Boolean isLogin = SharedPreferencesUtil.getBoolean(getApplicationContext(), Constants.APP_LOGIN_STATU_KEY, false);
                if (isLogin && GPSManager.getInstance() != null) {
                    //处于登录状态 退入后台重新唤醒 (重启 限速服务)
                    GPSManager.getInstance().startGPSListener();
                    //检测定位权限(仅限中山用户)
                    if (ServiceManager.getInstance().isStart(CheckLocPermissionService.class)) {
                        //如果启动过  证明是中山用户 ; 否者 不是中山用户 退入后台不用重启服务 立即检测权限是否开启
                        ServiceManager.getInstance().startService(activity, CheckLocPermissionService.class, null);
                    }
                }
            }*/

            Logger.i(TAG, "onActivityResumed " + activity);
        }

        @Override
        public void onActivityPaused(Activity activity) {
            //处理电源键 锁屏时不需提示app运行在后台
            if (pm == null) {
                pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
            }
            if(pm.isScreenOn()){
                Logger.i(TAG, "ScreenOn");
            }else{
                Logger.i(TAG, "ScreenOff");
                Constants.isSafety = true;
            }
            Logger.i(TAG, "onActivityPaused " + activity);
        }

        @Override
        public void onActivityStopped(Activity activity) {
            tempCount--;
            //处于后台
            if (tempCount == 0 && !Constants.isSafety) {
                Toast.makeText(getApplicationContext(), "智慧营维运行到后台!", Toast.LENGTH_SHORT).show();
                //弹出警示信息
                showNotification();
            }
            Logger.i(TAG, "onActivityStopped " + activity + " :  " + tempCount);
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            Logger.i(TAG, "onActivitySaveInstanceState " + activity + "" + outState);
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            Logger.i(TAG, "onActivityDestroyed " + activity);
            if (activity instanceof MainActivity) {
               /* if (GPSManager.getInstance() != null) {
                    GPSManager.getInstance().destory();
                }*/
                if (notificationManager != null) {
                    notificationManager.cancel(1);
                }
            }
        }
    };

    private boolean isFullScreen(Activity activity) {
        return (activity.getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN)==WindowManager.LayoutParams.FLAG_FULLSCREEN;
    }

    /**
     * 弹出通知提示
     */
    private void showNotification() {

        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mBuilder = new NotificationCompat.Builder(this);

            String appName = getString(getApplicationInfo().labelRes);
            int icon = getApplicationInfo().icon;

            Intent intent = new Intent(this,MainActivity.class);
            intent.setAction(Intent.ACTION_MAIN);
            // 修改vivo手机点击通知栏不返回
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 增加Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED用于正常的从后台再次返回到原来退出时的页面中
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            PendingIntent pendingInt = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            mBuilder.setOngoing(true)
                    .setAutoCancel(true)
                    .setWhen(System.currentTimeMillis())
                    .setDefaults(Notification.DEFAULT_VIBRATE)
                    .setContentText("正在后台运行...")
                    .setContentTitle(appName)
                    .setContentIntent(pendingInt)
                    .setSmallIcon(icon);
        }

        notificationManager.notify(1,mBuilder.build());

    }





}
